
{{template "base.html" .}}

{{define "content"}}
<script>
    $("#teacher-left-que").addClass("layui-nav-itemed")
    $("#teacher-left-que dl dd").eq(0).addClass("layui-this")
    //处理question数据表的option，score
    function editString(str){
        var s = str.split("[")[1]
        s=s.split("]")[0]
        s=s.split(" ")
        return s
    }
    //计算总分
    function sumscore(){
        var scoreList = []
        var maxscore =0
        $(".question-list-li").each(function (i,btn){
            $(btn).find(".options-question li").each(function (k,ltn){
                var score = Number($(ltn).find("span").text().split("分")[0])
                scoreList.push(score)

            })
            maxscore+=Math.max.apply(null,scoreList)
            scoreList =[]
        })
        $(".score-sum").text(maxscore)
        //计算总题数
        $(".question-sum").text($(".question-number").eq(-1).text().split(".")[0])
    }

    $(function(){
        //监听div高度变化计算总分
        $(".question-list-container").resize(function(){
            sumscore()
        });
        //动态生成html
        $.ajax({
            method: "get",
            url: "/teacher/Paper/"+$("#question-id").text(),
            success:function(res){
                if(res.code=='0'){
                    //绑定标题，备注
                    $(".question-list-title h1").text(res.PaperTitle)
                    $(".question-list-title div").text(res.paperContext)
                    //生成问题html
                    $(res.questions).each(function (){
                        $(".question-list-container").append($("#question-script").html())
                        questionSort()
                    })
                    $(".options-question").html("")
                    $(".question-list-li").each(function (i,btn){
                        //绑定问题数据
                        $(btn).find(".title-question span").text(res.questions[i].Question)
                        optionarrs=editString(res.questions[i].Options)
                        Scorearrs=editString(res.questions[i].Score)
                        $(optionarrs).each(function (k,v){
                            //绑定选项数据
                            var options="<li><input type=\"radio\" value=\"0\" disabled/><label>"+optionarrs[k]+"</label><span>"+Scorearrs[k]+"分</span></li>"
                            $(btn).find(".options-question").append(options)
                        })
                    })
                    $(".score-sum").text(res.PaperScore)
                    $(".score-Line").text(res.PaperScore_line)
                    sumscore()
                }
                else
                    window.location.replace("/404?msg="+res.msg);
            },
            error:function (data) {
                window.location.replace("/404?msg="+data);
            }
        })
    })
</script>
<div class="layui-row" style="height: auto;padding: 15px;min-width: 1100px">
    <div></div>
    <div class="layui-col-xs2 layui-col-sm2 layui-col-md2">
        <ul>
            <li><button type="button" class="layui-btn question-add"><i class="layui-icon layui-icon-add-1"></i>添加问题</button></li>
            <li><button type="button" class="layui-btn paper-settings" style="margin-top: 20px"><i class="layui-icon layui-icon-set-sm"></i>分数线</button></li>
        </ul>


        <div style="display: none">id:<span id="question-id">{{.paperId}}</span></div>
    </div>
    <div class="layui-col-xs10 layui-col-sm10 layui-col-md10" style="padding:0 25px;width: 898px;" >
        <div class="question-list" >
            <div class="question-list-title" title="编辑" onclick="titleEdit()">
                <h1 style="text-align: center"></h1>
                <div class="question-context"></div>
            </div>
            <div class="question-list-container" style="min-height: 569px" onchange="sumscore()">


            </div>

            <div class="question-list-footer">
                <div class="paper-stats">
                    <label>总分</label><span class="score-sum"></span>
                    <label>总题数</label><span class="question-sum"></span>
                    <label>低分预警</label><span class="score-Line">0</span>
                </div>
                <button type="button" class="layui-btn layui-btn-normal" onclick="questionSave()"><i class="layui-icon layui-icon-ok" style="margin-right: 6px;"></i>编辑保存</button>
            </div>
        </div>

        <!--问题-->
        <script type="text/html" id="question-script">
            <div class="question-list-li layui-anim layui-anim-upbit" title="编辑" onmouseenter="liMouseenter(this)" onmouseleave="liMouseleave(this)">
                <div class="div_preview" onclick="questionEdit(this)">
                    <div class="title-question"><i class="question-number"></i><span>问题</span></div>
                    <div class="options-question">
                        <li><input type="radio" value="0" disabled/><label>选项一</label><span>1分</span></li>
                    </div>
                </div>
            </div>
        </script>
        <!--编辑问题-->
        <script type="text/html" id="edit-question-script">
            <div class="div-edit-question layui-anim layui-anim-down ">
                <div class="div-edit-question_triangle"></div>
                <div class="div-edit-question-container">
                    <div class="layui-form-item">
                        <label class="label-edit-question">标题<i title="上传图片" style="float: right;font-size: 25px;" class="layui-icon layui-icon-picture" onclick="upPicture()"></i></label>
                        <div class="block-edit-question">
                            <input type="text" name="title" required="" lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input input-title">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="block-edit-question">
                            <table class="layui-table" >
                                <colgroup>
                                    <col width="450">
                                    <col width="100">
                                    <col>
                                </colgroup>
                                <thead>
                                <tr>
                                    <th>选项</th>
                                    <th>/</th>
                                    <th>分值<i title="锁定选项" style="float: right;font-size: 25px;" class="layui-icon layui-icon-password optionLock" onclick="optionLock(this)"></i></th>
                                </tr>
                                </thead>
                                <tbody>


                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="layui-form-item" style="text-align: center;">
                        <button  type="button" class="layui-btn btn-save-question" style="background-color: #ffab1a;width: 100%;">完成编辑</button>
                    </div>
                </div>
            </div>
        </script>
        <script type="text/html" id="add-tr">
            <tr class="table-list layui-anim layui-anim-downbit">
                <td><input type="text"  required="" lay-verify="required" placeholder="请输入选项" autocomplete="off" class="layui-input options-text"></td>
                <th><i onclick="add_tr(this)" title="在此选项下面插入一个新的选项" class="layui-icon layui-icon-addition table-add" ></i><i onclick="del_tr(this)" title="删除当前选项(保留一项)" class="layui-icon layui-icon-subtraction table-del"></i></th>
                <td><input  type="text" required="" lay-verify="required" placeholder="请输入分值" autocomplete="off" class="layui-input options-score" ></td>
            </tr>
        </script>
    </div>
</div>


<script>
    //问题锁定
    var LockColor
    var saveOption = []
    function optionLock(e){
        if ($(".optionLock").css("color")=="rgb(95, 95, 95)"){
            $(".optionLock").css("color","red");
            var tbody = Parents_findNode($(e),"tbody")
            tbody.find("tr").each(function (i,btn){
                saveOption[i]=$(btn).find(".options-text").val()+","+$(btn).find(".options-score").val()
            })
        }else {
            $(".optionLock").css("color","currentColor");
        }
        LockColor=$(".optionLock").css("color")
    }

    //从父类种寻找元素
    function Parents_findNode(e,s){
        var node = e.parents(".question-list-li").find(s)
        return node
    }
    //问题排序
    function questionSort(){
        $(".question-list-li").each(function (i,btn){
            $(this).find(".question-number").html(i+1+'.')  //问题的编号
            // $(this).attr("id","No."+i)                      //分配id
        })
    }
    //标题编辑
    function titleEdit(){
        layer.open({
            type: 2,
            title: '编辑标题',
            shadeClose: true,           //弹出框之外的地方是否可以点击
            offset: '10%',
            area: ['60%', '80%'],
            content: '/teacher/Paper/titleEdit',
            success:function (layero,index){
                //找到它的子窗口的body
                var body = layer.getChildFrame('body', index);  //巧妙的地方在这里哦
                //为子窗口元素赋值
                body.contents().find("#question-title").val($(".question-list-title h1").text());
                body.contents().find("#question-context").val($(".question-list-title div").text());
                body.contents().find("#question-id").val($("#question-id").text());
            },
        });
    }

    //插入编辑框
    function questionEdit(e){
        var nums = Parents_findNode($(e),".div-edit-question").length //编辑框个数
        if (nums==0){                                     //没有就添加
            $(".div-edit-question").remove();             //删除别的
            $(e).parent($(".question-list-li")).append($("#edit-question-script").html())
            var title = Parents_findNode($(e),".input-title")  //同步标题
            title.val($(e).find(".title-question span").text())
            var Lock = Parents_findNode($(e),".optionLock")    //锁的颜色
            Lock.css("color",LockColor)
            var tbody = Parents_findNode($(e),"tbody")          //同步选项

            //判断锁的颜色
            if (Lock.css("color")=="rgb(255, 0, 0)"){
                var options_question =$(e).find(".options-question")
                options_question.html("")
                $(saveOption).each(function (i,b){
                    tbody.append($("#add-tr").html())
                    tbody.find(".options-text").eq(i).val(b.split(",")[0])
                    tbody.find(".options-score").eq(i).val(b.split(",")[1])
                    var name = b.split(",")[0] //选项
                    var score = b.split(",")[1] //选项的分值
                    var options="<li><input type=\"radio\" value=\"0\" disabled/><label>"+name+"</label><span>"+score+"分</span></li>"
                    options_question.append(options)
                })
            }else {
                tbody.html("")
                $(e).find(".options-question li").each(function (i,btn){
                    var label = $(btn).find("label").text()
                    var span = $(btn).find("span").text().split("分")[0]
                    tbody.append($("#add-tr").html())
                    tbody.find(".options-text").eq(i).val(label)
                    tbody.find(".options-score").eq(i).val(span)
                })
            }

        }else {
            $(".div-edit-question").remove();
        }
    }

    //试卷对象
    var optionlist = []
    var scorelist = []

    function Question(name, option, score) {
        this.questionname = name;
        this.questionOption = option;
        this.optionScore = score;
    }


    //提交试卷
    function questionSave(){
        sumscore()
        var questionList = []
        $(".question-list-li").each(function (i,btn){
            var queTitle = $(btn).find(".title-question span").text()
            optionlist=[]
            scorelist=[]
            $(btn).find(".options-question li").each(function (i,btn2){
                var queoption = $(btn2).find("label").text()
                var quescore = $(btn2).find("span").text().split("分")[0]
                optionlist.push(queoption)
                scorelist.push(quescore)
            })
            var question = new Question(queTitle,optionlist,scorelist)
            questionList.push(question)  //传给后端的值
        })
        $.ajax({
            method: "post",
            url: "/teacher/Paper/edit/"+$("#question-id").text(),
            data: JSON.stringify(questionList),
            dataType:'JSON',
            success:function (res){
                if (res.code==0){
                    $.ajax({
                        method: "post",
                        url: "/teacher/Paper/set/"+$("#question-id").text(),
                        data: {
                            "score":$(".score-sum").text(),
                            "scoreLine":$(".score-Line").text(),
                        },
                        dataType:'JSON',
                    })
                    layer.msg("完成修改",{icon: 1, time: 1000},function (){
                        window.location.replace("/teacher/Paper");
                    });
                }else {
                    window.location.replace("/404?msg="+1);
                }
            },
            error:function (data) {
                window.location.replace("/404?msg="+data);
            }
        })
    }

    //新增一行
    function add_tr(e){
        $(e).parents("tr").after($("#add-tr").html())
    }//删除一行
    function del_tr(e){
        var tbody=$(e).parents("tbody")
        var options_question = Parents_findNode($(e),".options-question")
        var tr = $(e).parents("tr")
        if (tr.index()==0){

        }else {
            tr.remove()
        }
        options_question.html("")                         //同步选项
        tbody.find("tr").each(function (i,btn){
            var name = $(btn).find(".options-text").val() //选项
            var score = $(btn).find(".options-score").val() //选项的分值
            var options="<li><input type=\"radio\" value=\"0\" disabled/><label>"+name+"</label><span>"+score+"分</span></li>"
            options_question.append(options)
        })
    }

    //“完成编辑”按钮，关闭问题编辑框
    $(".question-list-container").on('click',".btn-save-question", function(e)
    {
        var div=$(e.target).parents(".div-edit-question")
        div.remove()
    })

    //监听 标题变化
    $(".question-list-container").on('input propertychange',".input-title", function(e)
    {
        //target 获取的是当前触发的那个对象，并不是绑定事件的那个对象
        var event = $(e.target)
        var node = Parents_findNode(event,".title-question span")
        node.text(event.val())
    })

    //监听 选项和分值变化
    $(".question-list-container").on('input propertychange',"tbody", function (e){
        updataOptions(e)
    })
    //更新编辑框选项
    function updataOptions(e)
    {
        var tbody=$(e.target).parents("tbody")
        var options_question = Parents_findNode($(e.target),".options-question")
        options_question.html("")
        tbody.find("tr").each(function (i,btn){
            var name = $(btn).find(".options-text").val() //选项
            var score = $(btn).find(".options-score").val() //选项的分值
            var options="<li><input type=\"radio\" value=\"0\" disabled/><label>"+name+"</label><span>"+score+"分</span></li>"
            // <li><input type="radio" value="0" disabled/><label>选项一</label><span>5分</span></li>
            options_question.append(options)
        })
    }

    //显示删除按钮
    var removeBut="<div class=\"remove\" title=\"删除\"><i class=\"layui-icon layui-icon-close\" onclick=\"questionRemove(this)\"></i></div>"
    function liMouseenter(e){
        $(e).append(removeBut)
    }
    function liMouseleave(e){
        $(e).find(".remove").remove()
    }
    //删除问题
    $(".question-list-container").on('click',".remove", function(e)
    {
        $(e.target).parents(".question-list-li").remove()
        questionSort()
        sumscore()
    })

    $(function(){
        //"添加问题"
        $(".question-add").click(function (){
            $(".question-list-container").append($("#question-script").html())
            questionSort()
            sumscore()
        })
        //"设置试卷"
        // 先调用layui.use()初始化模块
        layui.use(['layer', 'form'], function(){
            var layer = layui.layer;
            var form = layui.form;
            form.verify({
                number: [
                    /^$|^[0-9]*$/,
                    '必须为数字'
                ]
            });
            // 点击按钮弹出层
            $(".paper-settings").click(function (){
                var dom = "<form class=\"layui-form\">" +
                    "<div class=\"layui-form-item\" style='margin-top: 15px'>\n" +
                    "   <label class=\"layui-form-label\">输入框</label>\n" +
                    "   <div class=\"layui-input-block\">\n" +
                    "       <input style='width: 120px;' type=\"text\" name=\"title\" required=\"\" lay-verify=\"number\" placeholder=\"请输入分数线\"  autocomplete=\"off\" class=\"layui-input\">\n" +
                    "   </div>\n" +
                    "</div>" +
                    "<div class=\"layui-form-item\" style='margin: 0;border-bottom: 1px solid #f0f0f0;padding-bottom: 15px'>\n" +
                    "   <label class=\"layui-form-label\">开关</label>\n" +
                    "   <div class=\"layui-input-block\">\n" +
                    "       <input lay-filter=\"switchTest\" type=\"checkbox\" name=\"switch\" lay-skin=\"switch\" lay-text=\"ON|OFF\" lay-filter=\"switchTest\" value=\"1\">\n" +
                    "   </div>\n" +
                    "</div>" +
                    "<div class=\"layui-input-block\" style='margin: 0;text-align: center;padding: 15px'>\n" +
                    "            <button class=\"layui-btn \" lay-submit=\"\" lay-filter=\"score-Line-submit\">提交</button>\n" +
                    "            <button class=\"layui-btn layui-btn-primary score-Line-close\">关闭</button>\n" +
                    "          </div>" +
                    "</form>";

                // 打开弹出层
                layer.open({
                    type: 1,
                    value: $(".score-Line").text(),
                    title: '设置试卷分数线',
                    content: dom,
                    area: '275px',
                    success: function (layero, index) {
                        // 初始化layui表单元素
                        var scoreLine=$(".score-Line").text()

                        if (scoreLine=="关闭"){
                            $('input[name="title"]').val("");
                            $('input[name="title"]').prop("placeholder", "关闭");
                            $('input[name="title"]').prop("readonly", true);
                            $('input[name="switch"]').prop("checked", false);
                        }else {
                            $('input[name="title"]').val(scoreLine);
                            $('input[name="switch"]').prop("checked", true);
                        }
                        //监听开关
                        form.on('switch(switchTest)', function(data){
                            if(data.elem.checked){ //打开
                                $('input[name="title"]').val("");
                                $('input[name="title"]').prop("placeholder", "请输入分数");
                                $('input[name="title"]').prop("readonly", false);
                            }else{                 //关闭
                                $('input[name="title"]').val("");
                                $('input[name="title"]').prop("placeholder", "关闭");
                                $('input[name="title"]').prop("readonly", true);
                            }
                        });

                        form.on('submit(score-Line-submit)', function(data){
                            var value = layero.find("input[name='title']").val();
                            $(".score-Line").html(value)
                            if (value==""){
                                $(".score-Line").html("关闭")
                            }
                            layer.close(index);
                            return false;
                        });

                        $(".score-Line-close").click(function (){
                            layer.close(index);
                            return false
                        })
                        form.render();
                    },
                });
                $(".layui-layer-btn").css("text-align", "center");
            });
        });
    });


    function upPicture(){
        layui.use('upload', function(){
            var upload = layui.upload;
            //执行实例
            var uploadInst = upload.render({
                elem: '.layui-icon-picture' //绑定元素
                ,url: '/public/upload/'+getCookie("Id") //上传接口
                ,data:{  // 文件上传的参数
                    id: getCookie("Id"),
                    Status:"question",
                }
                ,done: function(res){
                    layer.msg(res.msg,{icon: res.icon, time: 1000},function(){
                        window.parent.location.reload()
                    }); //提交成功后刷新页面
                }
                ,error: function(){
                    //请求异常回调
                }
            });
        });
        return false
    }

</script>
<style>
    .layui-body{
        background: rgb(245, 245, 245);
    }
    .question-list{
        background-color:#FFFFFF;
        box-shadow: 0 2px 5px 0 #d9d9d9;
        border: 1px solid rgba(217,217,217,1);
        height: 830px;
        overflow-y:auto;
        position: relative;

    }

    .question-list-title{
        height: 150px;
        padding: 30px 0;
        border: none !important;
        border-bottom: 1px solid #e0e0e0 !important;
    }
    .question-context {
        padding: 0 60px;
        margin-top: 35px;
        font-size: 16px;
    }

    .question-list-li{
        line-height: 30px;
        border: none !important;
        border-bottom: 1px solid #e0e0e0 !important;
    }
    .question-list-li .remove{
        width: 50px;
        position: absolute;
        text-align: center;
        right: 0px;
        top: 0;
    }
    .question-list-li .remove:hover{
        cursor: pointer;
        background-color: #fafafa;
        border-bottom: 1px solid #e0e0e0 !important;
        border-left: 1px solid #e0e0e0 !important;
    }
    .question-list-li .remove i{
        font-size: 25px;
        vertical-align: middle;
    }
    .div-edit-question{
        position: relative;
        background: #fafafa;
        padding:20px 0;
        border-top: 1px solid #dfe4e6;
    }
    .div-edit-question_triangle{
        position: absolute;
        top: -12px;
        left: 84px;
        width: 24px;
        height: 12px;
        background-image: url("/static/images/triangle.png");
        background-size:100% 100%;
    }
    .div-edit-question-container{
        padding: 0 60px;
    }
    .block-edit-question{
        background-color: #FFFFFF;
    }
    .label-edit-question{
        position: relative;
        display: block;
        padding: 9px 15px;
        font-weight: 400;
        line-height: 20px;
        text-align: center;
        background-color: #f4f4f4;
        border-radius:5px 5px 0 0;
    }
    .table-add,.table-del{
        font-size: 20px;
        margin: 0 5px;
        display: inline-block;
    }
    .table-add:hover,.table-del:hover{
        color: #01aaed;
        cursor: pointer;
    }
    .div_preview:hover{
        background-color: #fafafa;
        cursor: pointer;
    }
    .question-list-footer{
        position: sticky;
        bottom: 0;
        height: 50px;
        background-color: #2F4056;
        width: 100%;
        line-height: 50px;
        z-index: 2;


    }
    .question-list-footer button{
        font-size: 18px;
        font-weight: bold;
        float: right;
        border-radius: 0;
        height: 100%;
        padding-left: 15px;
    }
    .div_preview{
        padding: 30px 60px;
    }
    .title-question{
        width: 100%;
        font-weight: bold;
        color: #444444;
        line-height: 20px;
        font-size: 18px;
    }
    .title-question i{
        font-size: 25px;
    }
    .options-question{

        padding-top: 10px;
    }
    .options-question li{
        padding-left: 15px;
        padding-top: 10px;
    }
    .options-question li input {
        vertical-align: middle;
        height: 16px;
        width: 18px;
        margin-right: 5px;
        margin-bottom: 3px;
    }
    .options-question li span{
        float: right;
    }
    .optionLock {
        color: rgb(95, 95, 95);
    }

    .paper-stats{
        float: left;
        color: #FFFFFF;
    }
    .paper-stats label{
        margin-left: 20px;
    }
    .paper-stats span{
        margin-left: 5px;
    }

</style>
{{end}}